/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import entities.User;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.aptech.session.beans.UserFacade;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import utils.Constants;

/**
 *
 * @author Chien
 */
@ManagedBean
@SessionScoped
public class UserControl implements Serializable {

    @EJB
    private UserFacade userFacade;
    /**
     * User is pricipal, authenticated user DO NOT UESE it, unless mofdify User
     * profile. user user is set only logon.
     */
    private User user;
    /**
     * selectedtuser is used as tempory user. Ex: select an user and show it's
     * profile
     */
    private User selectedtuser;
    /**
     * newUser: is use to add new user, can not use selectedUser, because of
     * changing selected User's profile
     */
    private User newUser = new User();
    boolean validEmail = false;
    private String email = "";
    private String avatar = "";
    /**
     * Used by newUser
     */
    private String newAvatar = "";

    public String getNewAvatar() {
        return newAvatar;
    }

    public void setNewAvatar(String newAvatar) {
        this.newAvatar = newAvatar;
    }

    public User getNewUser() {

        return newUser;
    }

    public void setNewUser(User newUser) {
        this.newUser = newUser;
    }
    private org.primefaces.component.calendar.Calendar dob = new org.primefaces.component.calendar.Calendar();

    public org.primefaces.component.calendar.Calendar getDob() {
         if (null != dob) {
            dob.setMaxdate(utils.Uility.maxDOB());
        }
        return dob;
    }
    

    public void setDob(org.primefaces.component.calendar.Calendar dob) {
        this.dob = dob;
    }

    /**
     * Upload image, ONLY USED with Edit login User's Profile (principal)
     *
     * @param event FileUploadEvent
     */
    public void handleFileUploadEditProfile(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg
                    avatar = Constants.DATABASE_IMAGE_PATH + time + ext;
                    if (null != user) {
                        user.setAvatar(avatar);
                    }
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + avatar);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }
    }

    /**
     * Upload image, ONLY USED with Edit login User's Profile (principal)
     *
     * @param event FileUploadEvent
     */
    public void handleFileUploadAddUser(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg

                    newAvatar = Constants.DATABASE_IMAGE_PATH + time + ext;
                    if (null != newUser) {
                        newUser.setAvatar(newAvatar);
                    }
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + avatar);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }


    }
    private boolean isShowError = false;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isValidEmail() {
        return validEmail;
    }

    public void setValidEmail(boolean validEmail) {
        this.validEmail = validEmail;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public User getSelectedtuser() {
        return selectedtuser;
    }

    public void setSelectedtuser(User selectedtuser) {
        this.selectedtuser = selectedtuser;
    }

    /**
     * Creates a new instance of UserControl
     */
    public UserControl() {
        user = new User();
        selectedtuser = new User();
       

    }

    public void gotoLoginpage() {
        FacesContext context = FacesContext.getCurrentInstance();
        String path = "/faces/userWeb/loginPage.xhtml";
        redicrectToPage(context, path);
    }

    public void checkEmail(ActionEvent actionEvent) {

        User checkUs = userFacade.checkEmail(getEmail());
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage("", new FacesMessage("Invalid email."));
        String path = "/faces/userWeb/loginPage.xhtml";
        if (null != checkUs) {
            redicrectToPage(context, path);
        }
    }

    public void forgotPassword() {
        FacesContext context = FacesContext.getCurrentInstance();
        String path = "/faces/userWeb/forgotPassword.xhtml";
        redicrectToPage(context, path);
    }

    /**
     * logout
     */
    public void logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        session.setAttribute("user", null);
        this.user = new User();
        try {
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/userWeb/loginPage.xhtml");
        } catch (Exception e) {
        }

    }

    private void redicrectToPage(FacesContext context, String path) {
        if (null == context) {
            return;
        }
        try {
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + path);
        } catch (Exception e) {
        }
    }

    /**
     * modified by Trong
     */
    public void checkLogin() {
        this.user = userFacade.checkLogin(user);
        FacesContext context = FacesContext.getCurrentInstance();
        String path = "/faces/userWeb/loginPage.xhtml";
//        user not found
        if (null == this.user) {
            redicrectToPage(context, path);
        }

        boolean isActive = this.user.getIsActive();
        // if not active
        if (!isActive) {
            redicrectToPage(context, path);
        }
        boolean role = user.getIsAdmin();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        session.setAttribute("user", user);
        if (role) {
            try {
                context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventManager.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/userWeb/home.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public List<User> getAllUser() {
        return userFacade.findAll();
    }

    public void delete(User user) {
        this.selectedtuser = user;
        userFacade.remove(user);
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/UserManager.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void savesetadmin(User user) {
        this.selectedtuser=user;
        userFacade.edit(user);
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/SetAdmin.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setfield() {
        user.setAddress("");
        user.setDepartmentName("");
        user.setEmail("");
        user.setFullName("");
        user.setPassWord("");
        user.setPhone("");
        user.setUserName("");
        user.setBirthday(null);
        user.setIsActive(false);
        user.setIsAdmin(false);
        user.setJoinedDate(null);

    }

    public void insert() {
        try {

            userFacade.create(newUser);
            // create new User for future creation, MUST HAVE
            newUser = new User();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Insert Success", ""));
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/UserManager.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void viewuser(User userdetail) {
        this.user = userdetail;
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/userWeb/Homeeditprofile.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void showDetail(User userdetail) {
        this.selectedtuser = userdetail;
        try {

            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/UpdateUser.xhtml");

        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void update() {
        try {
            selectedtuser.setAvatar(avatar);
            userFacade.edit(selectedtuser);
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/UserManager.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void updatepassword(User user) {
        this.selectedtuser=user;
        userFacade.edit(user);
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventManager.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void updateprofileuser(){
        try {
            user.setAvatar(avatar);
            userFacade.edit(user);
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/userWeb/home.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(UserControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public SelectItem[] sexoption() {
        SelectItem[] sexop = new SelectItem[3];
        sexop[0] = new SelectItem("");
        sexop[1] = new SelectItem("Male");
        sexop[2] = new SelectItem("Female");
        return sexop;
    }

    public SelectItem[] createFilterOptions() {
        SelectItem[] options = new SelectItem[8];
        options[0] = new SelectItem("");
        options[1] = new SelectItem("Manager");
        options[2] = new SelectItem("Maketing");
        options[3] = new SelectItem("Sales");
        options[4] = new SelectItem("IT");
        options[5] = new SelectItem("Accounting");
        options[6] = new SelectItem("Protection");
        options[7] = new SelectItem("Other");
        return options;
    }

    public String convertSex(User user) {
        if (null != user) {
            if (user.getSex()) {
                return "Male";

            } else {
                return "Female";
            }
        }
        return "";
    }
}
